package cn.honqun.tinycms.common.advice;

import cn.honqun.tinycms.common.dto.ReturnObject;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.webmvc.api.OpenApiWebMvcResource;
import org.springdoc.webmvc.ui.SwaggerConfigResource;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Nonnull;
import java.lang.reflect.Executable;
import java.util.Objects;

/**
 * 拦截所有标注了@RestController的类的方法，封装方法的返回对象为ReturnObject
 */
@Slf4j
@RestControllerAdvice
public class ReturnObjectAdvice implements ResponseBodyAdvice<Object> {
    /**
     * 根据给的的方法参数或者MessageConverter判断是否需要处理
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //如果是Swagger，则不处理
        Executable executable = methodParameter.getExecutable();
        if (Objects.equals(executable.getDeclaringClass(), SwaggerConfigResource.class)
                || Objects.equals(executable.getDeclaringClass(), OpenApiWebMvcResource.class)) {
            log.debug("Skip swagger request");
            return false;
        }
        //如果Controller类标注了@IgnoreResponse，则不处理
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponse.class)) {
            return false;
        }
        //如果方法标注了@IgnoreResponse，则不处理
        return !Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(IgnoreResponse.class);
    }

    /**
     * 在执行 {@code HttpMessageConverter} 之后且在调用其 write 方法之前调用。
     */
    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object o, @Nonnull MethodParameter methodParameter,
                                  @Nonnull MediaType mediaType, @Nonnull Class<? extends HttpMessageConverter<?>> aClass,
                                  @Nonnull ServerHttpRequest serverHttpRequest, @Nonnull ServerHttpResponse serverHttpResponse) {
        ReturnObject returnObject = ReturnObject.success();
        if (o != null) {
            if (o instanceof ReturnObject) {
                returnObject = (ReturnObject) o;
            } else {
                returnObject.data(o);
            }
        }

        return returnObject;
    }
}
